#include "netmanager.h"
#include "ui_netmanager.h"
#include "config/constants.h"

#include <QHostAddress>
#include <QMessageBox>
#include <config/config.h>

NetManager::NetManager(BaseForm *parent) :
    BaseForm(parent),
    ui(new Ui::NetManager)
{
    ui->setupUi(this);
    setFixedSize(320, 200);
    mymenu->hide();
    initWindow();
}

NetManager::~NetManager()
{
    delete ui;
}

void NetManager::initWindow()
{
    Config cfg;
    QVariant val = cfg.Get("Address", "ip");
    if(val.isValid())
    {
        QString tempIp = val.toString();

        QStringList ipList;
        ipList=tempIp.split(QRegExp("[.*/^]"));
        ui->edIP1->setText(ipList.at(0));
        ui->edIP2->setText(ipList.at(1));
        ui->edIP3->setText(ipList.at(2));
        ui->edIP4->setText(ipList.at(3));

        LOG_INFO << "====";
    }

    QVariant varPort = cfg.Get("Address", "port");
    if(varPort.isValid())
    {
        QString tempPort = varPort.toString();
        ui->edPort->setText(tempPort);
    }
}

void NetManager::on_btnConnect_clicked()
{
    QString strIP = ui->edIP1->text() + "." + ui->edIP2->text() + "." + ui->edIP3->text() + "." + ui->edIP4->text();

    QRegExp regExp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
    if(!regExp.exactMatch(strIP))
    {
        QMessageBox::information(this, "提示", "IP地址错误", QMessageBox::No);
        return;
    }

    ip = strIP;
    QString strPort = ui->edPort->text();
    int iPort = strPort.toInt();
    port = iPort;
    emit connectToNetSignals(strIP, iPort);
    emit connectToNet2000Signals(strIP, 2001);
}

void NetManager::netWorkStats()
{

}







void NetManager::on_btnDisconnect_clicked()
{
    LOG_DEBUG << "Disconnect net";
    emit netDisconnect();
}

void NetManager::netStateSlots(int e)
{
    LOG_DEBUG << "Net State " << e;
    if(e == QAbstractSocket::ConnectingState)
    {
        ui->ll_tcp_state->setText("正在连接网络...");
    }
    else if(e == QAbstractSocket::ConnectedState)
    {
        ui->ll_tcp_state->setText("网络连接成功！");
    }
    else if(e == QAbstractSocket::UnconnectedState)
    {
        ui->ll_tcp_state->setText("网络连接失败！");
    }
    else if(e == QAbstractSocket::BoundState)
    {
        ui->ll_tcp_state->setText("网络连接成功！");
    }
    //    LOG_DEBUG << "网络连接状态：" << e ;
}

void NetManager::netDisconnected()
{
    ui->ll_tcp_state->setText("网络连接断开！");
}

void NetManager::netConnected()
{
    ui->ll_tcp_state->setText("网络连接成功！");
    Config cfg;
    cfg.Set("Address", "ip", ip);
    QVariant val(port);
    cfg.Set("Address", "port", val);

    LOG_INFO << "写入IP地址: ip = " << ip.toStdString() << " port = " << port;
}
